﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Monkey.Warrenty.Data.Interfaces;
using Monkey.Warrenty.EntityModel;

namespace Monkey.Warrenty.Data
{
    public class SupplierGroupDao : ISupplierGroupDao
    {
        public List<SupplierGroup> GetAllSupplierGroups()
        {
            List<SupplierGroup> supplierGroups;

            using (var context = new MonkeyWarrantyEntities())
            {
                supplierGroups = context.SupplierGroups.OrderBy(x => x.Name).ToList();
            }

            return supplierGroups;
        }

        public SupplierGroup AddSupplierGroup(SupplierGroup supplierGroup)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                context.SupplierGroups.AddObject(supplierGroup);
                context.SaveChanges();
            }

            return supplierGroup;
        }

        public void UpdateSupplierGroup(SupplierGroup supplierGroup)
        {
            // throw new System.NotImplementedException();
            if (supplierGroup == null || supplierGroup.Id == 0) return;

            using (var context = new MonkeyWarrantyEntities())
            {
                context.SupplierGroups.Attach(supplierGroup);
                context.ObjectStateManager.ChangeObjectState(supplierGroup, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public void DeleteSupplierGroup(int supplierGroupId)
        {
            if (supplierGroupId <= 0) return;
            using (var context = new MonkeyWarrantyEntities())
            {
                var supplierGroup = context.SupplierGroups.First(g => g.Id == supplierGroupId);

                context.DeleteObject(supplierGroup);

                context.SaveChanges();
            }
        }

        public int GetMaxId()
        {
            var maxId = 0;

            using (var context = new MonkeyWarrantyEntities())
            {
                var dealerGroup = context.SupplierGroups.OrderByDescending(x => x.Id).FirstOrDefault();
                if (dealerGroup != null) maxId = dealerGroup.Id;
            }

            return maxId;
        }

        public int GetCurrentIdentity()
        {
            long? identity;
            using (var context = new MonkeyWarrantyEntities())
            {
                identity = context.GetIdentity("SupplierGroups").SingleOrDefault();
            }

            return identity.HasValue ? (int)identity.Value : 0;
        }

        public SupplierGroup GetById(int id)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                return context.SupplierGroups.FirstOrDefault(x => x.Id == id);
            }
        }
    }
}
